﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Web.Security;
using System.Web;
using FeCMS.Common.Enum;

namespace FeCMS.AccessControlModule.Security
{
    public class FeFormsPrincipal : IPrincipal
    {
        private IIdentity _identity;
        private UserInfo _userData;

        /// <summary>
        ///     
        /// </summary>
        /// <param name="ticket"></param>
        /// <param name="userData"></param>
        public FeFormsPrincipal(FormsAuthenticationTicket ticket, UserInfo userData)
        {
            if (ticket == null)
                throw new ArgumentNullException("ticket");
            if (userData == null)
                throw new ArgumentNullException("userData");

            _identity = new FormsIdentity(ticket);
            _userData = userData;
        }


        #region 属性

        public UserInfo UserData
        {
            get { return _userData; }
        }

        public IIdentity Identity
        {
            get { return _identity; }
        }

        #endregion

        /// <summary>
        ///     判断角色
        /// </summary>
        /// <returns></returns>
        public bool IsInRole(string role)
        {
            // 把判断用户组的操作留给UserData去实现
            IPrincipal principal = _userData as IPrincipal;
            if (principal == null)
                throw new NotImplementedException();
            else
                return principal.IsInRole(role);
        }


        /// <summary>
        ///     设置登录
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="userData">用户信息</param>
        /// <param name="expiration">过期时间</param>
        public static void SignIn(string loginName, UserInfo userData, int expiration)
        {
            if (string.IsNullOrEmpty(loginName))
                throw new ArgumentNullException("loginName");
            if (userData == null)
                throw new ArgumentNullException("userData");

            // 1. 把需要保存的用户数据转成一个字符串。
            string data = string.Empty;
            if (userData != null)
            {
                data = userData.ToString();
            }


            // 2. 创建一个FormsAuthenticationTicket，它包含登录名以及额外的用户数据。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                2, loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);


            // 3. 加密Ticket，变成一个加密的字符串。
            string cookieValue = FormsAuthentication.Encrypt(ticket);


            // 4. 根据加密结果创建登录Cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
            cookie.HttpOnly = true;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (expiration > 0)
                cookie.Expires = DateTime.Now.AddMinutes(expiration);

            HttpContext context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException();

            // 5. 写登录Cookie
            context.Response.Cookies.Remove(cookie.Name);
            context.Response.Cookies.Add(cookie);

        }

        /// <summary>
        ///     根据HttpContext对象设置用户标识对象
        /// </summary>
        /// <param name="context"></param>
        public static void TrySetUserInfo(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            FeFormsPrincipal user = TryParsePrincipal(context.Request);
            if (user != null)
            {
                context.User = user;
            }
        }


        /// <summary>
        ///     尝试从HttpRequest.Cookies中构造一个FeFormsPrincipal对象
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static FeFormsPrincipal TryParsePrincipal(HttpRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("context");

            //1. 读登录Cookie
            HttpCookie cookie = request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
            {
                return null;
            }

            try
            {
                UserInfo userData = new UserInfo();
                // 2. 解密Cookie值，获取FormsAuthenticationTicket对象
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
                {
                    //3. 还原用户数据  TODO:DLK 暂时简单化处理
                    string[] keyVal = ticket.UserData.Split('€');

                    if (keyVal.Length == 4)
                    {
                        long.TryParse(keyVal[0], out userData.UserId);
                        int.TryParse(keyVal[1], out userData.RoleId);
                        userData.UserName = keyVal[2];

                        int enumID;
                        int.TryParse(keyVal[3], out enumID);
                        userData.VisitorsType = (VisitorsType)enumID;
                    }

                }

                if (ticket != null && userData != null)
                {
                    // 4. 构造我们的MyFormsPrincipal实例，重新给context.User赋值。
                    return new FeFormsPrincipal(ticket, userData);
                }

            }
            catch {/* 有异常也不要抛出，防止攻击者试探。 */  }
            return null;
        }


        /// <summary>
        ///     登出
        /// </summary>
        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}
